<template>
  <el-dialog :visible.sync="value" :before-close="cancel">
    <template slot="title">自动出款条件设置</template>
    <el-form :model="form" ref="conditionsSetForm" :rules="conditionsSetRule" label-position="right" label-width="120px">
      <el-form-item label="名称" prop="conditionName">
        <el-col :span="6">
          <el-input @keyup.enter.native="doSave({action: 'saveForm', form: 'conditionsSetForm'})" type="input" v-model="form.conditionName"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="层级设置：" prop="levelId">
        <el-col :span="6">
          <el-select
            :collapse-tags="true"
            size="small"
            v-model="form.levelId" width="100%" multiple placeholder="请选择层级">
            <el-option label="代理"
                       :key="-1"
                       :value="-1">
            </el-option>
            <el-option
              v-for="item in tableData"
              :label="item.title"
              :key="item.value"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="金额区间设置" prop="minAmount">
        <el-col :span="6">
          <el-input @keyup.enter.native="doSave({action: 'saveForm', form: 'conditionsSetForm'})" v-model.number="form.minAmount" type="number" placeholder="请输入">
            <template slot="append">元</template>
          </el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="" prop="maxAmount">
        <el-col :span="6">
          <el-input @keyup.enter.native="doSave({action: 'saveForm', form: 'conditionsSetForm'})" v-model.number="form.maxAmount" type="number" placeholder="请输入">
            <template slot="append">元</template>
          </el-input>
        </el-col>
      </el-form-item>
      <p class="tips">注1：设置的区间中，金额可等于区间下限，不可等于区间上限</p>
      <p class="tips">注2：相同层级的金额区间不可有重叠部分</p>
      <div class="table-head">
        <label >三方出款商户：</label>
        <el-button type="primary" @click="doGet({action: 'getGrid'})">同步三方余额</el-button>
      </div>
      <el-form-item prop="merchantIds" class="el-form-item-ml0">
        <el-table border :data="merchantData"
                  ref="multipleTable"
                  v-loading="loading"
                  element-loading-text="加载中..."
                  @selection-change="handleSelectionChange"
                  class="el-table-align-center">
          <el-table-column type="selection" align="center" width="55"></el-table-column>
          <el-table-column label="三方出款商户" prop="merchantName" align="center"></el-table-column>
          <el-table-column label="商户号" prop="merchantCode" align="center"></el-table-column>
          <el-table-column label="三方账户余额" prop="" align="center">
            <template slot-scope="{row}">
              {{row.amount}}
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-col :span="12">
          <el-input @keyup.enter.native="doSave({action: 'saveForm', form: 'conditionsSetForm'})" type="textarea" v-model="form.remark"></el-input>
        </el-col>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="doSave({action: 'saveForm', form: 'conditionsSetForm'})" :loading="loading">确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>

  import {form} from '@/build'
  import {withdrawAutoUpdate,accountBalance} from '@/services/api/withdraw';
  import {getUserLevelList} from "@/services/api/userLevel";
  import {paymentWithdrawOverview} from "@/services/api/payment";
  export default {
    name: "auto-withdraw-dialog",
    mixins: [form],
    props: ['value','rowData'],
    data() {
      return {
        form: {
          id: this.rowData.id,
          conditionName: this.rowData.conditionName,
          withdrawType: this.rowData.withdrawType,
          minAmount: this.rowData.minAmount,
          maxAmount: this.rowData.maxAmount,
          levelId:  this.rowData.levelId != '' ? this.formatStr(this.rowData.levelId) : [],
          remark: this.rowData.remark,
          merchantIds: this.formatStr(this.rowData.merchantId),
          temp:this.formatStr(this.rowData.merchantId),
        },
        filters:{
          channelId:-1
        },
        tableData:[],
        merchantData:[],
        conditionsSetRule: {
          conditionName: [
            {required: true, message: '名称不能为空', trigger: 'blur'},
          ],
          minAmount: [
            {required: true, message: '最小金额不能为空', trigger: 'blur'},
          ],
          maxAmount: [
            {required: true, message: '最大金额不能为空', trigger: 'blur'},
          ],
          levelId: [
            {required: true, message: '请选择层级设置', trigger: 'blur'},
          ],
          merchantIds: [
            {type: 'array',required: true, message: '请选择三方出款商户'},
          ],
          remark: [
            {required: true, message: '备注不能为空'},
          ]
        },
      }
    },
    mounted() {
      this.bindGet(getUserLevelList, 'tableData', {
        format:(data)=>{
          let arr = []
          data.forEach((v,k)=>{
            arr.push({
              title:v.name,
              value:v.levelId,
            })
          })
          return arr
        }
      });
      this.bindSave(withdrawAutoUpdate, 'saveForm', 'form', {
        beforeSend:(data)=>{
          const {id,conditionName,minAmount,maxAmount,levelId,remark} = data
          return {
            id,
            conditionName,
            minAmount,
            maxAmount,
            levelId:levelId.join(','),
            merchantId:data.merchantIds.join(','),
            remark
          }
        },
        afterSuccess: () => {
          this.cancel()
          this.$parent.doGet({action: 'getGrid'})
        }
      });
      this.bindGet(paymentWithdrawOverview, 'merchantData',{
        action: 'getGrid',
        sendingData: 'filters',
        format:(data)=>{
          let arr = []
          data.forEach((v,k)=>{
            accountBalance({
              merchantId:v.merchantId
            }).then((data) => {
              this.$set(v,'amount',data[0]?(data[1] == -1 ? '不支持三方账户余额查询':data[1]):0)
              arr.push(v)
              if(this.form.temp.indexOf(v.merchantId) > -1){
                this.$refs.multipleTable.toggleRowSelection(v);
              }
            });
          })
          return arr
        }
      });
      this.getAll();
    },
    methods: {
      cancel() {
        this.$emit('input', false);
      },
      handleSelectionChange(val){
        this.form.merchantIds = val.map(item => item.merchantId);
      },
      formatStr(str){
        const arr = []
        str.split(',').forEach((v,k)=>{
          arr.push(Number(v))
        })
        return arr
      }
    },

  }
</script>

<style lang="scss" scoped>
  /deep/ .el-form-item-ml0 .el-form-item__content{
    margin-left: 0 !important;
  }
  .tips{
    color: #888888;
  }
  .table-head{
    display: flex;
    justify-content: space-between;
  }
  .el-table-align-center{
    margin: 20px 0;
  }
  .user-name{
    display: inline-block;
    min-width: 80px;
    line-height: 25px;
    border: 1px solid #ccc;
    text-align: center;
    border-radius: 30px;
    position: relative;
    margin:0 20px 20px 0;
    .user-name__close{
      display: block;
      width: 20px;
      height: 20px;
      position: absolute;
      top: -8px;
      right: -8px;
      font-size: 18px;
      cursor: pointer;
    }
  }
  .add-user{
    cursor: pointer;
  }
</style>
